#include "main.h"

void extractFiles (char * fileNames[])
{
	FILE * arc = NULL;
	FILE * fileToWrite = NULL;
	fileHead ** list;
	struct stat * fileStat = (struct stat *) calloc (1,sizeof(struct stat));
	char * tmpFileName;
	char yes[] = "Yes";
	char answer[256] = {0};
	char * pos;
	int m = 1;
	int flag = 0;
	int i = 0;
	int rc = 0;

	arc = fopen (fileNames[0],"rb");
	if (!arc)	cl_exit (EXTR_FILE_UI,OPEN_ERR);
	if ((rc = testing (arc)) == 1)	cl_exit (EXTR_FILE_UI,CS_ERR);
	rc = checkSign (arc);
	if (rc != 0)	cl_exit (EXTR_FILE_UI,SIGN_ERR);
	list = listingFile (arc);	
	while (list[i])
	{
		m = 1;
		while ( fileNames[m])
		{
			pos = getName (fileNames[m]);
			if (!(strcmp(list[i]->fileName,pos)))	list[i]->rplFlag = EXTR_FILE;
			m++;
		}
		i++;
	}
	i = 0;
	while (list[i])
	{
		flag = 1;
		if ((list[i]->rplFlag & EXTR_FILE))	{	
			fileToWrite = fopen (list[i]->fileName,"r");
			stat (list[i]->fileName,fileStat);
			if (fileToWrite)	{
				if (!(fileStat->st_mode & _S_IWRITE))	{
					printf ("This file will not be replaced %s\n",list[i]->fileName);
					list[i]->rplFlag = 0;
					fclose (fileToWrite);
				} else	{
					printf ("Do you want change %s? Input Yes or no: ",list[i]->fileName);
					scanf ("%s", answer);
					if (!strnicmp (yes,answer,3))	fclose (fileToWrite);
					else {
						list[i]->rplFlag = 0;	
						fclose (fileToWrite);
					}
				}
			}
			if (list[i]->rplFlag & EXTR_FILE)	{
				fileToWrite = fopen (list[i]->fileName,"wb");
				envInf.fileToWrite = fileToWrite;
				if (!fileToWrite)	cl_exit (EXTR_FILE_UI,OPEN_FILE_ERR);
			extrFile (fileToWrite,list[i],arc);
			}
		}
		i++;
	}
}